#!/usr/bin/env python3
#
#  Copyright 2016 The TMM/AD Authors. All rights reserved.
#  Use of this source code is governed by a BSD-style license that can be
#  found in the license.txt file.
#

import threading as _threading

#  File locks container.
_FILE_LOCKS = {}

#  Accessing lock of the container.
_ACCESS_LOCK = _threading.Lock()


def lock_file(path):
    """Lock specific file.

    :type path: str
    :param path: The file path.
    """

    #  Create the lock if it doesn't exist.
    _ACCESS_LOCK.acquire()
    if path not in _FILE_LOCKS:
        _FILE_LOCKS[path] = _threading.Lock()
    lock = _FILE_LOCKS[path]
    _ACCESS_LOCK.release()

    #  Do locking.
    lock.acquire()


def unlock_file(path):
    """Unlock specific file.

    :type path: str
    :param path: The file path.
    """

    #  Check the existence of the lock.
    _ACCESS_LOCK.acquire()
    if path not in _FILE_LOCKS:
        _ACCESS_LOCK.release()
        raise KeyError("No such lock.")
    lock = _FILE_LOCKS[path]
    _ACCESS_LOCK.release()

    #  Do unlocking.
    lock.release()
